#include "Widget_Reader.h"
#include "Common.h"
#include "DataBaseManager.h"

#include <QtGui/QGridLayout>
#include <QtGui/QAction>
#include <QtGui/QToolBar>
#include <QtGui/QSplitter>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlRecord>

#include <QtCore/QDebug>

namespace Jonathan
{

   /**
    * @brief Intializes a new reader widget.
    *
    * @param parent Parent widget hosting reader.
    */
   Widget_Reader::Widget_Reader(QWidget *parent) :
       QWidget(parent)
   {
      QWidget* widget = new QWidget (this);
      this->m_Reader = new Widget_Reader_TextBox (widget);
      this->m_Title = new QLabel (widget);
      this->m_Title->setMaximumHeight (25);
      this->m_Title->setAlignment (Qt::AlignHCenter | Qt::AlignVCenter);
      //this->m_Title->setMargin (0);
      this->m_Title->setStyleSheet (Common::GetLabelStyle ());

      QGridLayout* layout = new QGridLayout (widget);
      layout->setMargin (0);
      layout->setSpacing (0);
      layout->addWidget (this->m_Title, 0, 0);
      layout->addWidget (this->m_Reader, 1, 0);
      widget->setLayout (layout);

      this->m_BookList = new QTreeWidget (this);
      this->m_BookList->setHeaderHidden (true);
      connect (this->m_BookList, SIGNAL (itemSelectionChanged ()),
               this, SLOT (TreeItemChanged ()));

      QSplitter* splitter = new QSplitter(Qt::Horizontal, this);
      splitter->addWidget (this->m_BookList);
      splitter->addWidget (widget);
      splitter->setCollapsible (0, true);
      splitter->setCollapsible (1, false);
      splitter->setStretchFactor (0, 1);
      splitter->setStretchFactor (1, 3);

      QToolBar* toolBar = new QToolBar (this);
      toolBar->setIconSize (QSize (16, 16));
      toolBar->addAction (Common::GetIcon (Jonathan::ICON_Previous_Chapter), "Previous Chapter");
      toolBar->addAction (Common::GetIcon (Jonathan::ICON_Next_Chapter), "Next Chapter",
                          this, SLOT (NextChapter ()));
      toolBar->addSeparator ();

      layout = new QGridLayout (this);
      layout->setMargin (0);
      layout->setSpacing (0);
      layout->addWidget (toolBar, 0, 0);
      //layout->addWidget (this->m_Reader, 1, 0);
      layout->addWidget (splitter, 1, 0);
      setLayout (layout);
   }

   void Widget_Reader::PreviousChapter ()
   {
   }

   void Widget_Reader::NextChapter ()
   {
   }

   /**
    * @brief Sets the tab index.
    *
    * @param index Index of tab in tab control.
    */
   void Widget_Reader::SetTabIndex (int index)
   {
      this->m_TabIndex = index;
   }

   /**
    * @brief Starts a reading operation with the given parameters.
    *
    * @param book TreeItem_Book to use.
    * @param subBook Name of sub book, if any.
    * @param chapter Chapter to open.
    */
   void Widget_Reader::Read (TreeItem_Book* book, QString subBook, QString chapter)
   {
      this->m_Book = book;
      this->m_Title->setText (book->GetName ());
      this->m_BookList->clear ();
      for (int a = 0; a < book->childCount (); a++)
      {
         QTreeWidgetItem* childItem = book->child (a);
         QTreeWidgetItem* newSubItem = new QTreeWidgetItem (this->m_BookList);
         newSubItem->setText (0, childItem->text (0));
         newSubItem->setIcon (0, childItem->icon (0));
         if (book->HasSubBooks ())
         {
            newSubItem->setData (0, Qt::UserRole, Jonathan::SubBook);
            QSqlQuery query = book->GetDatabase ().exec ("SELECT ChapterCount FROM book_list WHERE Name='" +
                                                         newSubItem->text (0) + "';");
            if (query.next ())
            {
               int numChapters = query.value (0).toInt ();
               for (int a = 1; a <= numChapters; a++)
               {
                  QTreeWidgetItem* newChapterItem = new QTreeWidgetItem (newSubItem);
                  newChapterItem->setText (0, QString::number (a));
                  newChapterItem->setIcon (0, Common::GetIcon (Jonathan::ICON_Chapter));
                  newChapterItem->setData (0, Qt::UserRole, Jonathan::Chapter);
                  if (newChapterItem->text (0) == chapter && newSubItem->text (0) == subBook)
                  {
                     newChapterItem->setSelected (true);
                     newSubItem->setExpanded (true);
                  }
                  newSubItem->addChild (newChapterItem);
               }
            }
         }
         else
         {
            newSubItem->setData (0, Qt::UserRole, Jonathan::Chapter);
            if (newSubItem->text (0) == chapter)
               newSubItem->setSelected (true);
         }
         this->m_BookList->addTopLevelItem (newSubItem);
      }
   }


   /**
    * @brief Starts a reading operation with the given parameters.
    *
    * @param subBook Name of sub book, if any.
    * @param chapter Chapter to open.
    */
   void Widget_Reader::Read (QString subBook, QString chapter)
   {
      if (chapter == Common::PREFACE)
      {
         QSqlQuery query = this->m_Book->GetDatabase ().exec ("SELECT Summary FROM book_info;");
         if (query.next ()) this->m_Reader->setHtml (query.value (0).toString ());
      }
      else
      {
         QSqlQuery query = this->m_Book->GetDatabase ().exec ("SELECT * FROM book_text WHERE Chapter=" + chapter +
                          ((subBook.isNull () || subBook.isEmpty ()) ? ";" : " AND Book='" + subBook + "';"));
         QString readerText = Common::TableStart ();
         bool highlight = true;
         while (query.next ())
         {
            QSqlRecord record = query.record ();
            QString chapter = record.value (Common::CHAPTER).toString ();
            QString verse = record.value (Common::VERSE).toString ();
            QString text = record.value (Common::TEXT).toString ();
            QString heading = record.value (Common::HEADER).toString ();

            if (!heading.isNull () && !heading.isEmpty ())
            {
               readerText.append ("<tr");
               if (highlight) readerText.append (" style=\"background-color:E8E8E8;\"");
               readerText.append ("><td></td>");
               readerText.append ("<td align=\"center\"><small><blockquote>");
               readerText.append (heading);
               readerText.append ("</blockquote></small></td><td></td></tr>");
            }

            readerText.append ("<tr");
            if (highlight) readerText.append (" style=\"background-color:E8E8E8;\"");
            readerText.append ("><td valign=\"top\" style=\"color:DarkRed; font-weight:bold;\" align=\"right\">");
            readerText.append (chapter + ":" + verse);
            readerText.append ("</td><td style=\"padding-left:5px;\">");
            // TODO: change to anchors.
            readerText.append (text.replace ("href=\"\"", "href=\"nonsense\""));
            readerText.append ("</td><td valign=\"top\" style=\"color: DarkRed; font-weight:bold;\" align=\"left\">");
            readerText.append (chapter + ":" + verse);
            readerText.append ("</td></tr>");
            highlight = !highlight;
         }
         readerText.append ("</table></body></html>");
         this->m_Reader->setHtml (readerText);
      }
      this->m_Book->GetDatabase ().close ();

      QString title = this->m_Book->GetBookAbbreviation ()+ " | " ;
      if (!subBook.isNull () && !subBook.isEmpty ())
         title += subBook + " - ";
      title += chapter;
      emit TitleChanged (title, this->m_TabIndex);
   }

   /**
    * @brief Occurs when the selected on the book list tree changes.
    *
    */
   void Widget_Reader::TreeItemChanged ()
   {
      QTreeWidgetItem* selectedItem = this->m_BookList->selectedItems ().first ();
      if (selectedItem)
      {
         int itemType = selectedItem->data (0, Qt::UserRole).toInt ();
         if (itemType == Jonathan::Chapter)
         {
            QString subBook;
            if (selectedItem->parent ())
               subBook = selectedItem->parent ()->text (0);

            this->Read (subBook, selectedItem->text (0));
         }
      }
   }

}
